

"""
UDP_Client及UDP_Server定义
"""

import socket


class UDP_Client:
    def __init__(self, queue):
        # self.ADDR_List = ADDR_List
        self.udpCliSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.queue = queue

    def send(self, ADDR_List, sendinfo):
        # print(ADDR_List, sendinfo)
        self.udpCliSock.sendto(sendinfo, ADDR_List)

    def run(self):
        while True:
            if not self.queue.empty():
                sendinfo = self.queue.get()
                if isinstance(sendinfo, str):
                    self.send(str(sendinfo).encode())
                else:
                    self.send(sendinfo)


class UDP_Server:
    def __init__(self, port, queue):
        self.port = port
        self.udpSerSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.udpSerSock.bind(('', self.port))
        self.queue = queue

    def run(self):
        BUFSIZE = 32 * 1024
        while True:
            data, addr = self.udpSerSock.recvfrom(BUFSIZE)
            # print("Receive from %s:%s" % addr)
            # print("Msg: ", data)
            self.queue.put(data)

